#!/bin/bash
#
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# A helper script to initialise an empty $DIR
# If you use volumes then Docker will copy the $DIR content from the container to the volume.
# If you use bind mounts, that does not happen, so we do it here.

set -e

if [[ "$VERBOSE" == "yes" ]]; then
    set -x
fi

if [[ -n "${NO_INIT_VAR_SOLR:-}" ]]; then
    exit 0
fi

DIR=${1:-/var/solr}

if [ ! -d "$DIR" ]; then
    echo "Missing $DIR"
    exit 1
fi

function check_dir_writability {
    local dir="$1"
    if [ ! -w "$dir" ]; then
        echo "Cannot write to $dir as $(id -u):$(id -g)"
        ls -ld "$dir"
        exit 1
    fi
}

if [ ! -d "$DIR/data" ]; then
    echo "Creating $DIR/data"
    check_dir_writability "$DIR"
    mkdir "$DIR/data"
    chmod 0770 "$DIR/data"
fi

if [ ! -d "$DIR/logs" ]; then
    echo "Creating $DIR/logs"
    check_dir_writability "$DIR"
    mkdir "$DIR/logs"
    chmod 0770 "$DIR/logs"
fi

if [ ! -f "$DIR/data/solr.xml" ]; then
    echo "Copying solr.xml"
    cp -a /opt/solr/server/solr/solr.xml "$DIR/data/solr.xml"
fi

if [ ! -f "$DIR/data/zoo.cfg" ]; then
    echo "Copying zoo.cfg"
    cp -a /opt/solr/server/solr/zoo.cfg "$DIR/data/zoo.cfg"
fi

if [ ! -f "$DIR/log4j2.xml" ]; then
    echo "Copying log4j2.xml"
    cp -a /opt/solr/server/resources/log4j2.xml "$DIR/log4j2.xml"
fi

